package com.sql.common.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;

/**
 * Created by dell on 2017/9/19.
 */
public class FieldSetter {

    /**
     * 设置属性，直接赋值
     */
    public static void setFieldSetter(Class<?> clazz, Object obj, String fieldName, Object value) throws Exception {
        Field f = clazz.getDeclaredField(fieldName);
        f.setAccessible(true);
        f.set(obj,value);
        f.setAccessible(false);
    }

    /**
     * 设置属性值，可以使用a.b.c这样的方式级联设置属性值
     * @param clazz
     * @param obj
     * @param fieldName
     * @param value
     * @throws Exception
     */
    public static void setFieldByWriteMethod(Class<?> clazz, Object obj, String fieldName, Object value) throws Exception {
        String[]fieldNames;
        if(fieldName.contains(".")){
            fieldNames=fieldName.split("[.]");
        }else{
            fieldNames=new String[]{fieldName};
        }
        Object lastValue=null;
        Class<?> tempClazz=null;
        for(int i=0;i<fieldNames.length;i++){
            if(lastValue==null){
                tempClazz=clazz;
            }
            PropertyDescriptor p = new PropertyDescriptor(fieldNames[i],tempClazz);
            Field f=getFieldByName(tempClazz,fieldNames[i]);
            if(f==null) break;
            if(i<fieldNames.length-1){
                lastValue=p.getReadMethod().invoke(obj,null);
                if(lastValue==null)
                    lastValue=f.getType().newInstance();
            }else{
                lastValue=value;
            }
            p.getWriteMethod().invoke(obj,lastValue);
            tempClazz=f.getType();
        }
    }

    public static Field getFieldByName(Class<?> clazz, String name){
        Field f=null;
        try {
            f = clazz.getDeclaredField(name);
        } catch (NoSuchFieldException e) {
        }
        if(f==null){
            return getFieldByName(clazz.getSuperclass(),name);
        }
        return f;
    }
}
